package jjn.carl.backtrack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * @author Jjn
 * @since 2023/7/29 16:28
 */
public class LeetCode51 {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> result = new ArrayList<>();
        char[][] board = new char[n][n];
        for (char[] c : board) {
            Arrays.fill(c, '.');
        }
        backtrack(n, result, 0, board);
        return result;
    }
    
    private void backtrack(int n, List<List<String>> result, int row, char[][] board) {
        if (row == n) {
            List<String> snapshot = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                snapshot.add(new String(board[i]));
            }
            result.add(snapshot);
            return;
        }
        for (int column = 0; column < n; column++) {
            if (isOkay(board, row, column, n)) {
                board[row][column] = 'Q';
                backtrack(n, result, row + 1, board);
                board[row][column] = '.';
            }
        }
    }
    
    private boolean isOkay(char[][] board, int row, int column, int n) {
        for (int i = 0; i < n; i++) {
            if (board[i][column] == 'Q') {
                return false;
            }
        }
        for (int i = row - 1, j = column - 1; i >= 0 && j >= 0; i--, j--) {
            if (board[i][j] == 'Q') {
                return false;
            }
        }
        for (int i = row - 1, j = column + 1; i >= 0 && j <= n - 1; i--, j++) {
            if (board[i][j] == 'Q') {
                return false;
            }
        }
        return true;
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int i = scanner.nextInt();
        List<List<String>> lists = new LeetCode51().solveNQueens(i);
        System.out.println(String.join(",", lists.toString()));
    }
}
